/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.hagopa.games.moneypool.utils;

import java.security.*;

/**
 *
 * @author igorg
 */
public class UsefulUtils {
    private static final char[] hexChars ={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    
    public static String hexStringFromBytes(byte[] b)
     {

        String hex = "";
        int msb;
        int lsb = 0;
        int i;

        // MSB maps to idx 0
        for (i = 0; i < b.length; i++)
        {
            msb = ((int)b[i] & 0x000000FF) / 16;
            lsb = ((int)b[i] & 0x000000FF) % 16;
            hex = hex + hexChars[msb] + hexChars[lsb];
        }
        return(hex);
   }
   


    public static String getMD5(String clientIp, String key, String serialized_content) throws NoSuchAlgorithmException
    {
        System.out.println("[Utils][getMD5] IP=" + clientIp + ", Key=" + key + ", content=" + serialized_content);
        MessageDigest algorithm = MessageDigest.getInstance("MD5");
        String dataString = clientIp + key + serialized_content;
        byte data2hash[] = dataString.getBytes();
        algorithm.reset();
        algorithm.update(data2hash);

        return hexStringFromBytes(algorithm.digest());
    }
    public static String getSHA1(String clientIp, String key, String serialized_content) throws NoSuchAlgorithmException
    {
        MessageDigest algorithm = MessageDigest.getInstance("SHA-1");
        String dataString = clientIp + key + serialized_content;
        byte data2hash[] = dataString.getBytes();
        algorithm.reset();
        algorithm.update(data2hash);
        return hexStringFromBytes(algorithm.digest());
    }
}
